<template>
  <div class="monitoring-page">
    <!-- 日期选择器 -->
    <van-cell title="选择单个日期" :value="selectedDate" @click="showCalendar = true" />
    <van-calendar
      v-model:show="showCalendar"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onDateConfirm"
      color="rgba(101, 242, 13, 0.622)"
    />

    <!-- 班级选择框 -->
    <van-field
      v-model="selectedClass"
      is-link
      readonly
      label="选择班级"
      placeholder="选择班级"
      @click="showClassPicker = true"
    />
    <van-popup v-model:show="showClassPicker" round position="bottom">
      <van-picker
        :columns="classOptions"
        show-toolbar
        @cancel="showClassPicker = false"
        @confirm="onClassConfirm"
      />
    </van-popup>

    <!-- 上传视频按钮 -->
    <div v-if="role !== 2" class="add-attendance-button">
      <van-button
        type="primary"
        @click="showUploadPopup = true"
        size="small"
        round
        color="rgba(101, 242, 13, 0.622)"
      >
        上传视频
      </van-button>
    </div>

    <!-- 上传视频表单 -->
    <van-popup v-model:show="showUploadPopup" round position="bottom">
      <van-form>
        <van-field v-model="uploadDate" label="上传日期" is-link readonly @click="showUploadCalendar = true" placeholder="选择日期" />
        <van-calendar v-model:show="showUploadCalendar" :min-date="minDate" :max-date="maxDate" @confirm="onUploadDateConfirm" color="rgba(101, 242, 13, 0.622)" />

        <van-field v-model="uploadClass" label="上传班级" is-link readonly @click="showUploadClassPicker = true" placeholder="选择班级" />
        <van-popup v-model:show="showUploadClassPicker" round position="bottom">
          <van-picker :columns="classOptions" @confirm="onUploadClassConfirm" @cancel="showUploadClassPicker = false" />
        </van-popup>

        <van-field v-model="uploadFileName" label="上传视频" readonly placeholder="选择视频" @click="triggerFileInput" />
        <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" />

        <div class="van-popup__footer">
          <van-button round block type="warning" @click="showUploadPopup = false">取消</van-button>
          <van-button round block type="info" native-type="submit" @click="onFileChange">提交</van-button>
        </div>
      </van-form>
    </van-popup>

    <div class="monitoring-content">
      <div class="monitoring-list-container">
        <van-swipe-cell
          v-for="video in filteredVideos"
          :key="video.id"
          :right-width="120"
          stop-propagation
        >
          <template #right>
            <div class="swipe-actions" v-if="role !== 2">
              <van-button square type="primary" @click="showUpdateVideoPopup(video)" icon="edit"></van-button>
              <van-button square type="danger" @click="confirmDeleteVideo(video.id)" icon="delete"></van-button>
            </div>
          </template>
          <div class="monitoring-item">
            <div class="monitoring-title-box">
              <div class="monitoring-info-container">
                <div class="monitoring-info">
                  <div class="monitoring-title">班级ID: {{ video.classId }}</div>
                  <div class="monitoring-detail">
                    <div class="monitoring-preview">
                      <div class="monitoring-preview-content">
                        <van-tag type="primary" size="large">时间: {{ formatDate(video.time) }}</van-tag>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="monitoring-media">
                  <video v-if="video.videoUrl" :src="getFullVideoUrl(video.videoUrl)" controls class="monitoring-video"></video>
                </div>
              </div>
            </div>
          </div>
        </van-swipe-cell>
      </div>
    </div>

    <!-- 修改视频信息表单 -->
    <van-popup v-model:show="showUpdatePopupState" round position="bottom">
      <van-form>
        <van-field v-model="updateVideoDate" label="修改日期" is-link readonly @click="showUpdateCalendar = true" placeholder="选择日期" />
        <van-calendar v-model:show="showUpdateCalendar" :min-date="minDate" :max-date="maxDate" @confirm="onUpdateDateConfirm" color="rgba(101, 242, 13, 0.622)" />

        <van-field v-model="updateVideoClass" label="修改班级" is-link readonly @click="showUpdateClassPicker = true" placeholder="选择班级" />
        <van-popup v-model:show="showUpdateClassPicker" round position="bottom">
          <van-picker :columns="classOptions" @confirm="onUpdateClassConfirm" @cancel="showUpdateClassPicker = false" />
        </van-popup>

        <van-field v-model="updateFileName" label="修改视频" readonly placeholder="选择视频" @click="triggerUpdateFileInput" />
        <input type="file" ref="updateFileInput" @change="handleUpdateFileChange" style="display: none;" />

        <div class="van-popup__footer">
          <van-button round block type="warning" @click="showUpdatePopupState = false">取消</van-button>
          <van-button round block type="info" native-type="submit" @click="onUpdateVideo">确定</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { getOssPrefix } from '@/v-api/properties';
import { Toast, Dialog } from 'vant';

const selectedDate = ref('');
const showCalendar = ref(false);
const selectedClass = ref('');
const showClassPicker = ref(false);
const classOptions = ref([]);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date();
const prefix = getOssPrefix();
const role = ref(null);
const videos = ref([]);
const filteredVideos = ref([]);

const showUploadPopup = ref(false);
const uploadDate = ref('');
const showUploadCalendar = ref(false);
const uploadClass = ref('');
const showUploadClassPicker = ref(false);
const uploadFile = ref(null);
const uploadFileName = ref('');

const showUpdatePopupState = ref(false);
const updateVideoId = ref(null);
const updateVideoDate = ref('');
const showUpdateCalendar = ref(false);
const updateVideoClass = ref('');
const showUpdateClassPicker = ref(false);
const updateFile = ref(null);
const updateFileName = ref('');

const getTodayDate = () => {
  const today = new Date();
  return today.toISOString().split('T')[0];
};

onMounted(async () => {
  selectedDate.value = getTodayDate();
  await fetchRole();
  await fetchClasses();
});

const fetchRole = async () => {
  try {
    const response = await axios.get('/api/student/role');
    const data = response.data.data;
    role.value = data.role;

    if (role.value === 3) {
      await fetchVideosByStudentId(data.id);
    } else {
      await fetchVideos();
    }

    console.log('Role:', role.value);
  } catch (error) {
    console.error('Failed to fetch role:', error);
  }
};

const fetchVideosByStudentId = async (studentId) => {
  try {
    const response = await axios.get(`/api/monitoring/videos?studentId=${studentId}`);
    videos.value = response.data.data;
    filterVideosByDate();
    console.log('Videos for Student:', videos.value);
  } catch (error) {
    console.error('Failed to fetch videos by student ID:', error);
    videos.value = [];
  }
};

const fetchVideos = async () => {
  try {
    const response = await axios.get('/api/monitoring/videos');
    videos.value = response.data.data;
    filterVideosByDate();
    console.log('Videos:', videos.value);
  } catch (error) {
    console.error('Failed to fetch videos:', error);
    videos.value=[];
  }
};

const fetchClasses = async () => {
  try {
    const response = await axios.get('/api/monitoring/classes');
    const classes = response.data.data;
    classOptions.value = classes.map(classId => ({
      text: `Class ${classId}`,
      value: classId
    }));
  } catch (error) {
    console.error('Failed to fetch classes:', error);
  }
};

const onClassConfirm = async (value) => {
  selectedClass.value = value.text;
  showClassPicker.value = false;
  await fetchVideosByClassId(value.value);
};

const fetchVideosByClassId = async (classId) => {
  try {
    const response = await axios.get(`/api/monitoring/videos?classId=${classId}`);
    videos.value = response.data.data;
    filterVideosByDate();
  } catch (error) {
    console.error('Failed to fetch videos by class ID:', error);
  }
};

const triggerFileInput = () => {
  document.querySelector('input[type="file"]').click();
};

const triggerUpdateFileInput = () => {
  document.querySelector('input[type="file"]').click();
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  uploadFile.value = file;
  uploadFileName.value = file.name;
};

const handleUpdateFileChange = (event) => {
  const file = event.target.files[0];
  updateFile.value = file;
  updateFileName.value = file.name;
};

const onFileChange = async () => {
  if (!uploadClass.value || !uploadDate.value || !uploadFile.value) {
    Toast.fail('请先选择日期、班级和视频文件');
    return;
  }
  const formData = new FormData();
  formData.append('file', uploadFile.value);
  formData.append('classId', uploadClass.value.split(' ')[1]);
  formData.append('time', uploadDate.value);

  try {
    const response = await axios.post('/api/monitoring/upload', formData);
    Toast.success(response.data.message);
    await fetchVideosByClassId(uploadClass.value.split(' ')[1]);
    showUploadPopup.value = false;
  } catch (error) {
    console.error('Failed to upload video:', error);
    Toast.fail('视频上传失败: ' + error.response.data.message);
  }
};

const confirmDeleteVideo = (videoId) => {
  Dialog.confirm({
    title: '确认删除',
    message: '您确定要删除这个视频吗？'
  }).then(() => {
    deleteVideo(videoId);
  }).catch(() => {
    Toast.fail('取消删除');
  });
};

const deleteVideo = async (videoId) => {
  try {
    const response = await axios.delete(`/api/monitoring/delete/${videoId}`);
    Toast.success(response.data.message);
    await fetchVideosByClassId(selectedClass.value.split(' ')[1]);
  } catch (error) {
    console.error('Failed to delete video:', error);
    Toast.fail('删除视频失败: ' + error.response.data.message);
  }
};

const showUpdateVideoPopup = (video) => {
  updateVideoId.value = video.id;
  updateVideoDate.value = video.time;
  updateVideoClass.value = `Class ${video.classId}`;
  updateFileName.value = video.videoUrl;
  showUpdatePopupState.value = true;
};

const onUpdateVideo = async () => {
  if (!updateVideoId.value) {
    Toast.fail('视频ID缺失');
    return;
  }

  const formData = new FormData();
  formData.append('id', updateVideoId.value);

  if (updateVideoDate.value) {
    formData.append('time', updateVideoDate.value);
  }

  if (updateVideoClass.value) {
    formData.append('classId', updateVideoClass.value.split(' ')[1]);
  }

  if (updateFile.value) {
    formData.append('file', updateFile.value);
  }

  try {
    const response = await axios.put('/api/monitoring/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    Toast.success(response.data.message);
    showUpdatePopupState.value = false;
    await fetchVideosByClassId(updateVideoClass.value.split(' ')[1]);
  } catch (error) {
    console.error('Failed to update video:', error);
    Toast.fail('更新视频失败: ' + error.response.data.message);
  }
};

const getFullVideoUrl = (url) => {
  return prefix + url;
};

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

const filterVideosByDate = () => {
  if (!selectedDate.value) {
    filteredVideos.value = videos.value;
    return;
  }
  filteredVideos.value = videos.value.filter(video => {
    const videoDate = new Date(video.time);
    return videoDate.toISOString().split('T')[0] === selectedDate.value;
  });
};

const onDateConfirm = (date) => {
  date.setDate(date.getDate() + 1);
  selectedDate.value = date.toISOString().split('T')[0];
  showCalendar.value = false;
  filterVideosByDate();
};

const onUploadDateConfirm = (date) => {
  date.setDate(date.getDate() + 1);
  uploadDate.value = date.toISOString().split('T')[0];
  showUploadCalendar.value = false;
};

const onUpdateDateConfirm = (date) => {
  date.setDate(date.getDate() + 1);
  updateVideoDate.value = date.toISOString().split('T')[0];
  showUpdateCalendar.value = false;
};

const onUploadClassConfirm = (value) => {
  uploadClass.value = value.text;
  showUploadClassPicker.value = false;
};

const onUpdateClassConfirm = (value) => {
  updateVideoClass.value = value.text;
  showUpdateClassPicker.value = false;
};
</script>

<style scoped>
.monitoring-content {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.swipe-actions {
  display: flex;
  flex-direction: column;
}

.monitoring-item {
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.monitoring-title {
  font-size: 20px;
  margin-bottom: 5px;
}

.monitoring-info {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.monitoring-date {
  margin-right: 20px;
}

.monitoring-title-box {
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.monitoring-info-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitoring-video {
  max-width: 150px;
  max-height: 150px;
  border-radius: 4px;
}

.choose {
  display: flex;
  align-items: center;
  gap: 10px;
}

.video-upload {
  margin-top: 20px;
}

.monitoring-actions {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.van-popup__footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
}
</style>
